package com.viish.apps.tripletriad.reseau;

import java.io.IOException;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;

public class BlueConnection extends Thread implements iReseau
{
	public static final String NOM = "";
	public static final String UUID_CODE = "";
	
	private boolean isServer, isConnected;
	private BluetoothAdapter blueAdapter;
	private BluetoothDevice blueDevice;
	private BluetoothServerSocket blueSSocket;
	private BluetoothSocket blueSocket;
	
	public BlueConnection(boolean server, BluetoothDevice device)
	{
		isServer = server;
		isConnected = false;
		blueDevice = device;
		blueAdapter = BluetoothAdapter.getDefaultAdapter();
	}
	
	@Override
	public void run()
	{
		if (isServer)
			runServer();
		else
			runClient();
	}
	
	public void initServer()
	{
		BluetoothServerSocket tmp = null;
		
        try 
        {
            tmp = blueAdapter.listenUsingRfcommWithServiceRecord(NOM, UUID.fromString(UUID_CODE));
        } 
        catch (Exception e) { e.printStackTrace(); }
        
        blueSSocket = tmp;
	}
	
	public void initClient()
	{
		BluetoothSocket tmp = null;

        try 
        {
            tmp = blueDevice.createRfcommSocketToServiceRecord(UUID.fromString(UUID_CODE));
        } 
        catch (Exception e) { e.printStackTrace(); }
        
        blueSocket = tmp;
	}
	
	public void runServer()
	{
		boolean waitingforconnect = true;
		blueSocket = null;
        while (waitingforconnect) 
        {
            try 
            {
                blueSocket = blueSSocket.accept();
            } 
            catch (IOException e) 
            {
                break;
            }
            
            if (blueSocket != null) 
            {
            	waitingforconnect = false;
            	isConnected = true;
                try 
                {
					blueSSocket.close();
				} 
                catch (Exception e) { e.printStackTrace(); }
                break;
            }
        }
        
        while (isConnected)
        {
        	// TODO
        }
	}
	
	public void runClient()
	{
		blueAdapter.cancelDiscovery();

        try 
        {
            blueSocket.connect();
            isConnected = true;
        } 
        catch (Exception e) 
        { e.printStackTrace(); }

        while (isConnected)
        {
        	// TODO
        }
	}
	
	@Override
	public void send(String s)
	{
		if (isConnected && blueSocket != null)
		{
			//TODO
		}
	}
	
	@Override
	public String recv()
	{
		return "";
	}
	
	public void close()
	{
		if (isConnected && blueSocket != null)
		{
			try
			{
				blueSocket.close();
				isConnected = false;
			}
			catch (Exception e) { e.printStackTrace(); }
		}	
	}
}
